﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.SystemHelp;
using Aliyeye.Car.Net.UI.PrintExport;

namespace Aliyeye.Car.Net.UI.OrderModel
{
    public partial class ReturnIllegalInfo : Aliyeye.Car.Net.UI.BaseForm
    {
        private Aliyeye.Car.Net.UI.PageDataSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.PageDataSvc.SoapHeaderClass();
        private int reserveID = 0;
        DataSet ds = null;
        decimal returnAmount = 0;

        public ReturnIllegalInfo()
        {
            InitializeComponent();
        }

        public ReturnIllegalInfo(int resvID)
        {
            InitializeComponent();
            this.reserveID = resvID;
        }

        private void ReturnIllegalInfo_Load(object sender, EventArgs e)
        {
            BindInfo();
        }

        string carCode = string.Empty;
        DateTime beginTime = new DateTime(1900, 1, 1);
        DateTime endTime = new DateTime(1900, 1, 1);
        string illeglKeys = "";

        private void BindInfo()
        {
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;

            string _strSql = "Reserve.Id='" + reserveID + "'";   // "IsReturnIllegal ='false' ";
            PageDataSvc.PageData value = new Aliyeye.Car.Net.UI.PageDataSvc.PageData();
            value.TableName = "Reserve left join Car on Car.Id=Reserve.CarId left join Customer on Customer.Id=Reserve.CustId";
            value.PrimaryKey = "Reserve.Id";
            value.OrderStr = "Reserve.InpuTime desc";
            value.PageIndex = "1";
            value.PageSize = "1";
            value.QueryCondition = _strSql;
            value.QueryFieldName = "Reserve.CustId,IsReturnIllegal,Reserve.BookTime,Reserve.EndBooktime,Reserve.Id as ReserveID,Reserve.Code as ReserveCode,Customer.Code,SettlementDate,ComName,Name,ReceivedAmount,  IllegalRetention,((select sum(Price)  from Illegal where Illegal.CarCode=Car.Code and Reserve.BookTime<=Illegal.Time and Illegal.Time<=Reserve.EndBooktime)-case when TotalFines is null then 0 else TotalFines end) as IllegalSumAmount,(select Count(*)  from Illegal where Illegal.Status='未结算' and Illegal.CarCode=Car.Code and Reserve.BookTime<=Illegal.Time and Illegal.Time<=Reserve.EndBooktime) as IllegalCount,Customer.Custype,Car.code as CarCode,Car.Cartype,Car.Brand";
            value.Group = "";

            ServiceManipulator.SafeAsyncExecution<PageDataSvc.PageDataServiceSoapClient>(
                proxy => proxy.GetList(sopaHeader, value),
                result =>
                {
                    if (result.Error == null)
                    {
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        ds = (DataSet)result.Result;
                        if (ds != null)
                        {
                            if (ds.Tables[0].Rows[0]["IsReturnIllegal"].ToString().Trim() != "")
                            {
                                modelReserve.IsReturnIllegal = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsReturnIllegal"].ToString());
                            }
                            else
                            {
                                modelReserve.IsReturnIllegal = false;
                            }

                            if (modelReserve.IsReturnIllegal)
                            {
                                isSave = true;
                                btnSave.Enabled = false;
                            }
                            modelReserve.Id = Convert.ToInt32(ds.Tables[0].Rows[0]["ReserveID"].ToString());
                            modelReserve.ReturnIllegalDate = DateTime.Now;
                            modelReserve.ReturnIllegalUserID = Login.LogUserId;
                            modelReserve.CustId = Convert.ToInt32(ds.Tables[0].Rows[0]["CustId"].ToString());

                            lblReserveCode.Text = ds.Tables[0].Rows[0]["ReserveCode"].ToString();
                            lblCustomerCode.Text = ds.Tables[0].Rows[0]["Code"].ToString();
                            lblCustomerComp.Text = ds.Tables[0].Rows[0]["ComName"].ToString();
                            lblCustomerName.Text = ds.Tables[0].Rows[0]["Name"].ToString();
                            lblCustomerType.Text = ds.Tables[0].Rows[0]["Custype"].ToString().Trim() == "1" ? "个人用户" : "企业用户";
                            lblCarBrand.Text = ds.Tables[0].Rows[0]["Brand"].ToString();
                            lblCarCode.Text = ds.Tables[0].Rows[0]["CarCode"].ToString();
                            lblCartype.Text = ds.Tables[0].Rows[0]["Cartype"].ToString();
                            lblReturnDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

                            lblIllegalRetention.Text = ds.Tables[0].Rows[0]["IllegalRetention"].ToString();
                            string IllSumAmount = ds.Tables[0].Rows[0]["IllegalSumAmount"].ToString();
                            if (string.IsNullOrEmpty(IllSumAmount))
                                lblIllegalSumAmount.Text = "0";
                            else
                                lblIllegalSumAmount.Text = "-" + IllSumAmount;

                            lblIllegalCount.Text = ds.Tables[0].Rows[0]["IllegalCount"].ToString() + " 笔";

                            returnAmount = Convert.ToDecimal(lblIllegalRetention.Text) + Convert.ToDecimal(lblIllegalSumAmount.Text);
                            modelReserve.ReturnIllegalAmount = returnAmount;
                            lblReturnIllegalAmount.Text = returnAmount.ToString();

                            lblUserName.Text = Login.LogTrueName;

                            //车辆信息
                            carCode = lblCarCode.Text = ds.Tables[0].Rows[0]["CarCode"].ToString();
                            beginTime = modelReserve.BookTime = Convert.ToDateTime(ds.Tables[0].Rows[0]["BookTime"].ToString());
                            endTime = modelReserve.EndBooktime = Convert.ToDateTime(ds.Tables[0].Rows[0]["EndBooktime"].ToString());

                            IllegalSvc.SoapHeaderClass sopaHeaderIllegal = new Aliyeye.Car.Net.UI.IllegalSvc.SoapHeaderClass();
                            IllegalSvc.IllegalServiceSoapClient IllegalClient = new Aliyeye.Car.Net.UI.IllegalSvc.IllegalServiceSoapClient();

                            DataSet dsIllegalKeys = IllegalClient.GetKeysByCarCode(sopaHeaderIllegal, carCode, beginTime, endTime);
                            if (dsIllegalKeys != null && dsIllegalKeys.Tables[0].Rows.Count > 0)
                            {
                                foreach (DataRow dr in dsIllegalKeys.Tables[0].Rows)
                                    illeglKeys += dr["Id"].ToString().Trim() + ",";
                                illeglKeys = illeglKeys.Substring(0, illeglKeys.Length - 1);
                            }

                        }
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        bool isSave = false;
        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (!isSave)
            {
                if (PageCommon.Confirm("你还未结算，现在结算吗？"))
                {
                    SaveInfo();
                }
                else
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }

        ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();
        ReserveSvc.Reserve modelReserve = new Aliyeye.Car.Net.UI.ReserveSvc.Reserve();

        private void SaveInfo()
        {
            ServiceManipulator.SafeAsyncExecution<ReserveSvc.ReserveServiceSoapClient>(
            proxy => proxy.ReturnIllegal(sopaHeaderReserveSvc, modelReserve),
            result =>
            {
                if (result.Error == null)
                {
                    //更改违章付款状态
                    IllegalSvc.SoapHeaderClass sopaHeaderIllegal = new Aliyeye.Car.Net.UI.IllegalSvc.SoapHeaderClass();
                    IllegalSvc.IllegalServiceSoapClient IllegalClient = new Aliyeye.Car.Net.UI.IllegalSvc.IllegalServiceSoapClient();
                    if (illeglKeys != "")
                        IllegalClient.GetUpdateStatusByKeysByCarCode(sopaHeaderIllegal, carCode, beginTime, endTime, illeglKeys);

                    PageCommon.Notify("违章保留结算成功！");
                    overlay.FadeOut(); Cursor.Current = Cursors.Default;

                    isSave = true;
                    btnSave.Enabled = false;
                }
                else
                {
                    PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                }
            },
            this
            );
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveInfo();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (!isSave)
            {
                PageCommon.Alert("请先结算，在打印单据！");
                return;
            }

            DataSet dsCom = null;
            CompanySvc.SoapHeaderClass sopaHeaderCompany = new CompanySvc.SoapHeaderClass();
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            ServiceManipulator.SafeAsyncExecution<CompanySvc.CompanyServiceSoapClient>(
                    proxy => proxy.GetList(sopaHeaderCompany, ""),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            dsCom = (DataSet)result.Result;
                            if (dsCom.Tables[0].Rows.Count > 0)
                            {
                                Model.Company model = new Model.Company();

                                model.ComName = dsCom.Tables[0].Rows[0]["ComName"].ToString();
                                model.ComAddr = dsCom.Tables[0].Rows[0]["ComAddr"].ToString();
                                model.Tel = dsCom.Tables[0].Rows[0]["Tel"].ToString();
                                model.UserName = dsCom.Tables[0].Rows[0]["UserName"].ToString();
                                model.Url = dsCom.Tables[0].Rows[0]["Url"].ToString();
                                model.Marks = dsCom.Tables[0].Rows[0]["Marks"].ToString();

                                //开始打印结算单
                                WordHelper wordHelp = new WordHelper();
                                if (wordHelp.PrintReturnIllegalInfo(ds, returnAmount, model))
                                {
                                    PageCommon.Notify("打印成功！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                                else
                                {
                                    PageCommon.Alert("打印失败！");
                                    overlay.FadeOut(); Cursor.Current = Cursors.Default;
                                }
                            }
                            else
                            {
                                PageCommon.Alert("打印失败！");
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
        }

        private void lklblShowDetails_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BillingDetailsList show = new BillingDetailsList(this.reserveID);
            show.ShowDialog();
        }

        private void picbBills_Click(object sender, EventArgs e)
        {
            BillingDetailsList show = new BillingDetailsList(this.reserveID);
            show.ShowDialog();
        }

    }
}
